<?php

namespace common\service;

use common\exception\LogicException;
use common\model\ReviewFeedbackConfirmModel;
use common\model\ReviewFeedbackModel;
use Exception;
use support\ErrorCode;
use support\SingletonTrait;

class ReviewFeedbackConfirmService
{
    use SingletonTrait;


    /**
     * 确认
     * @param     $reviewFeedbackId
     * @param int $userId
     * @return array|bool
     * @throws Exception
     */
    public function confirm($reviewFeedbackIds, int $userId)
    {
        $reviewFeedbackIds = split_array($reviewFeedbackIds);
        $reviewFeedbackList = model(ReviewFeedbackModel::class)
            ->where(['id' => ['in', $reviewFeedbackIds]])
            ->column('id');
        if (empty($reviewFeedbackList)) {
            throw new LogicException("review feedback not found", ErrorCode::REVIEW_FEEDBACK_NOT_FOUND);
        }
        $rfcList = model(ReviewFeedbackConfirmModel::class)
            ->where(['review_feedback_id' => ['in', $reviewFeedbackIds], 'user_id' => $userId])
            ->field('id, review_feedback_id')
            ->select();
        $rfcList = array_column($rfcList, 'id', 'review_feedback_id');
        $addItems = [];
        $modifyItems = [];
        $time = time();
        foreach ($reviewFeedbackList as $rfId) {
            if (!isset($rfcList[$rfId])) {
                $addItems[] = ['review_feedback_id' => $rfId, 'user_id' => $userId, 'confirm_at' => $time];
            } else {
                $modifyItems[] = ['id' => $rfcList[$rfId], 'confirm_at' => $time];
            }
        }
        $res = [];
        if (!empty($addItems)) {
            $res = model(ReviewFeedbackConfirmModel::class)->addAll($addItems);
        }
        foreach ($modifyItems as $mod) {
            $res[] = model(ReviewFeedbackConfirmModel::class)->modifyItem($mod);
        }
        return $res;
    }

    /**
     * 确认人员列表
     * @param int $reviewFeedbackId
     * @return array|false|mixed|string
     */
    public function confirmList(int $reviewFeedbackId)
    {
        return model(ReviewFeedbackConfirmModel::class)
            ->alias('r')
            ->join('user u on u.id = r.user_id')
            ->field('u.id,u.name,u.avatar,r.confirm_at')
            ->where(['review_feedback_id' => $reviewFeedbackId])
            ->select();

    }

    /**
     * 取消确认
     * @param int $reviewFeedbackId
     * @param int $userId
     * @return false|float|int|mixed|string
     */
    public function cancel(int $reviewFeedbackId, int $userId)
    {
        $rfc = model(ReviewFeedbackConfirmModel::class)->where(['review_feedback_id' => $reviewFeedbackId, 'user_id' => $userId])->find();
        if (empty($rfc)) {
            return 0;
        }
        return model(ReviewFeedbackConfirmModel::class)->where(['id' => $rfc['id']])->delete();
    }
}